package com.wlit.alarm.service;

import cn.hutool.core.net.url.UrlBuilder;
import com.alibaba.fastjson.JSONObject;
import com.wlit.alarm.utils.SmsUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * Http API处理
 */
@ChannelHandler.Sharable
public class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private static String[] commands ={"sendSms","callPhone","getConf","getRSSI","reset","hangup"};

    private AsciiString contentType = HttpHeaderValues.APPLICATION_JSON;

    private static List<String> commandList = new ArrayList<>();

    private IAlarmService alarmService;

    public HttpHandler(IAlarmService alarmService) {
        this.alarmService = alarmService;
        for (String command : commands) {
            commandList.add(command);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

        String urlStr = request.getUri();

        if (request.getMethod()!= HttpMethod.POST){
            JSONObject data = new JSONObject();
            data.put("code", 500);
            data.put("msg", "错误的请求方法");
            writeErrorResopnse(ctx, data);
        }

        if (!alarmService.isOpen()) {
            JSONObject data = new JSONObject();
            data.put("code", 500);
            data.put("msg", "串口未开启");
            writeErrorResopnse(ctx, data);
            return;
        }

        ByteBuf body = request.content();
        byte[] reqContent = new byte[body.readableBytes()];
        body.readBytes(reqContent);
        String strContent = new String(reqContent, StandardCharsets.UTF_8);
        if (strContent == null || strContent.length() == 0){
            JSONObject data = new JSONObject();
            data.put("code", 500);
            data.put("msg", "请求内容不能为空");
            writeErrorResopnse(ctx, data);
            return;
        }

        JSONObject jsonObject = JSONObject.parseObject(strContent);
        String command = (String) jsonObject.getString("command");
        System.out.println("收到请求：" + command);

        if (command == null || command.length() == 0) {
            JSONObject data = new JSONObject();
            data.put("code", 500);
            data.put("msg", "command不能为空");
            writeResopnse(ctx, data);
            return;
        }

        if (!commandList.contains(command)) {
            JSONObject data = new JSONObject();
            data.put("code", 500);
            data.put("msg", "不支持的command");
            writeResopnse(ctx, data);
            return;
        }

        byte[] bytes = null;
        switch (command) {
            case "sendSms": {
                String phone = (String) jsonObject.getString("phone");
                String content = (String) jsonObject.getString("content");
                if (phone == null || content == null) {
                    JSONObject data = new JSONObject();
                    data.put("code", 500);
                    data.put("msg", "参数错误");
                    writeResopnse(ctx, data);
                    return;
                }
                bytes = SmsUtils.buildSms(phone, content, 4);
            }
            break;

            case "callPhone": {
                String phone = (String) jsonObject.getString("phone");
                String content = (String) jsonObject.getString("content");
                if (phone == null || content == null) {
                    JSONObject data = new JSONObject();
                    data.put("code", 500);
                    data.put("msg", "参数错误");
                    writeResopnse(ctx, data);
                    return;
                }
                bytes = SmsUtils.buildVoice(phone, content);
            }
            break;

            case "getConf":
                bytes = SmsUtils.buildConfiguration();
                break;

            case "getRSSI":
                bytes = SmsUtils.buildRSSI();
                break;

            case "reset":
                bytes = SmsUtils.buildReset();
                break;

            case "hangup":
                bytes = SmsUtils.buildHangup();
                break;

            default:
                break;
        }
        if (bytes != null) {
            alarmService.send(bytes);
        }

        JSONObject data = new JSONObject();
        data.put("code", 200);
        data.put("msg", "请求已发送");
        writeResopnse(ctx, data);

    }

    private void writeResopnse(ChannelHandlerContext ctx, JSONObject data) {
        String str = data.toJSONString();
        ByteBuf buf = Unpooled.wrappedBuffer(str.getBytes());
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
        HttpHeaders heads = response.headers();
        heads.add(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=UTF-8");
        heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        ctx.writeAndFlush(response);
    }

    private void writeErrorResopnse(ChannelHandlerContext ctx, JSONObject data) {
        String str = data.toJSONString();
        ByteBuf buf = Unpooled.wrappedBuffer(str.getBytes());
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE, buf);
        HttpHeaders heads = response.headers();
        heads.add(HttpHeaderNames.CONTENT_TYPE, contentType + "; charset=UTF-8");
        heads.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        ctx.writeAndFlush(response);
    }
}
